﻿using ImageProcessing.Comm.LogHelp;

using Newtonsoft.Json;

using System.Collections.Generic;
using System.Text;

namespace ImageProcessing.HttpRequest
{
    /// <summary>
    /// Http Request
    /// </summary>
    public class HttpRequests : IHttpRequests
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILoggerHelper<HttpRequests> _loggerHelper;

        public HttpRequests(IHttpClientFactory clientFactory, ILoggerHelper<HttpRequests> loggerHelper)
        {
            _clientFactory = clientFactory;
            _loggerHelper = loggerHelper;
        }

        /// <summary>
        ///  Post Request And RequestHeaders
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Url">Url</param>
        /// <param name="Content">Content</param>
        /// <param name="RequestHeadersDic">RequestHeadersDic</param>
        /// <returns></returns>
        public async Task<T> PostAsync<T>(string Url, object Content, Dictionary<string, string> RequestHeadersDic)
        {
            var log = "";
            try
            {
                //序列化成json
                Content = JsonConvert.SerializeObject(Content);
                log += $"Url为{Url}，内容为{Content}" + Environment.NewLine;
                //创建请求的客户端
                var client = _clientFactory.CreateClient();
                //添加请求头
                foreach (var item in RequestHeadersDic)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }

                //创建请求类型
                var content = new StringContent(Content.ToString(), Encoding.UTF8, "application/json");
                var response = await client.PostAsync(Url, content);
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                var result = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrWhiteSpace(result))
                {
                    log += $"请求结果为空{response.Content.ReadAsStringAsync().Result}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                log += $"请求结果为:{response.Content.ReadAsStringAsync().Result}" + Environment.NewLine;
                try
                {
                    var data = JsonConvert.DeserializeObject<T>(result);
                    log += $"序列化成功";
                    _loggerHelper.Info(log);
                    return data;
                }
                catch
                {
                    //不返回错误信息直接向外抛错误，外部捕获
                    throw;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.Error($"post request exception  日志信息为{log}", ex);
                return default;
                throw;
            }
        }

        /// <summary>
        /// Post Request
        /// </summary>
        /// <param name="Url">Url</param>
        /// <param name="Content">Content</param>
        /// <returns></returns>
        public async Task<T> PostAsync<T>(string Url)
        {
            var log = "";
            try
            {
                _loggerHelper.Info("PostAsync" + DateTime.Now + "发送请求");

                //创建请求的客户端
                var client = _clientFactory.CreateClient();
                //创建请求类型
                var content = new StringContent("", Encoding.UTF8, "application/json");
                var response = await client.PostAsync(Url, content);
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                var result = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrWhiteSpace(result))
                {
                    log += $"请求结果为空{response.Content.ReadAsStringAsync().Result}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                log += $"请求结果为:{response.Content.ReadAsStringAsync().Result}" + Environment.NewLine;
                try
                {
                    var data = JsonConvert.DeserializeObject<T>(result);
                    log += $"序列化成功";
                    _loggerHelper.Info(log);
                    _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求");
                    return data;
                }
                catch
                {
                    _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 catch");
                    //不返回错误信息直接向外抛错误，外部捕获
                    throw;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 Exception");
                _loggerHelper.Error($"post request exception  日志信息为{log}", ex);
                return default;
                throw;
            }
        }

        /// <summary>
        /// Post Request
        /// </summary>
        /// <param name="Url">Url</param>
        /// <param name="Content">Content</param>
        /// <returns></returns>
        //public async Task<T> PostAsync<T>(string Url, object Content)
        //{
        //    var log = "";
        //    try
        //    {
        //        _loggerHelper.Info("PostAsync" + DateTime.Now + "发送请求");
        //        //序列化成json
        //        Content = JsonConvert.SerializeObject(Content);
        //        log += $"Url为{Url}，内容为{Content}" + Environment.NewLine;
        //        //创建请求的客户端
        //        var client = _clientFactory.CreateClient();
        //        //创建请求类型
        //        var content = new StringContent(Content.ToString(), Encoding.UTF8, "application/json");
        //        var response = await client.PostAsync(Url, content);
        //        if (!response.IsSuccessStatusCode)
        //        {
        //            log += $"请求失败{JsonConvert.SerializeObject(response)}";
        //            _loggerHelper.Warn(log);
        //            return default;
        //        }
        //        var result = response.Content.ReadAsStringAsync().Result;
        //        if (string.IsNullOrWhiteSpace(result))
        //        {
        //            log += $"请求结果为空{response.Content.ReadAsStringAsync().Result}";
        //            _loggerHelper.Warn(log);
        //            return default;
        //        }
        //        log += $"请求结果为:{response.Content.ReadAsStringAsync().Result}" + Environment.NewLine;
        //        try
        //        {
        //            var data = JsonConvert.DeserializeObject<T>(result);
        //            log += $"序列化成功";
        //            _loggerHelper.Info(log);
        //            _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求");
        //            return data;
        //        }
        //        catch
        //        {
        //            _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 catch");
        //            //不返回错误信息直接向外抛错误，外部捕获
        //            throw;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 Exception");
        //        _loggerHelper.Error($"post request exception  日志信息为{log}", ex);
        //        return default;
        //        throw;
        //    }
        //}

        ///// <summary>
        ///// Post Request
        ///// </summary>
        ///// <param name="Url">Url</param>
        ///// <param name="Content">Content</param>
        ///// <returns></returns>
        //public async Task<T> PostAsync<T>(string Url, object Content)
        //{
        //    var log = "";
        //    try
        //    {
        //        //序列化成json
        //        Content = JsonConvert.SerializeObject(Content);
        //        //创建请求的客户端
        //        var client = _clientFactory.CreateClient();
        //        //创建请求类型
        //        var content = new StringContent(Content.ToString(), Encoding.UTF8, "application/json");
        //        var response = await client.PostAsync(Url, content);
        //        if (!response.IsSuccessStatusCode)
        //        {
        //            _loggerHelper.Warn(log);
        //            return default;
        //        }
        //        var result = response.Content.ReadAsStringAsync().Result;
        //        if (string.IsNullOrWhiteSpace(result))
        //        {
        //            _loggerHelper.Warn(log);
        //            return default;
        //        }
        //        return default;
        //    }
        //    catch (Exception ex)
        //    {
        //        _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 Exception");
        //        _loggerHelper.Error($"post request exception  日志信息为{log}", ex);
        //        return default;
        //        throw;
        //    }
        //}
        public async Task<Stream> PostAsync<T>(string Url, Dictionary<string, string> Content, byte[] a, byte[] b)
        {
            var log = "";
            try
            {
                // 创建一个字典来存储固定的参数
                var fixedParams = new Dictionary<string, string>()
{
    { "ldmSteps", "25" },
    { "ldmSampler", "plms" },
    { "zitsWireframe", "true" },
    { "hdStrategy", "Crop" },
    { "hdStrategyCropMargin", "196" },
    { "hdStrategyCropTrigerSize", "800" },
    { "hdStrategyResizeLimit", "2048" },
    { "prompt", "" }, // 假设prompt为空字符串，根据实际情况填写
    { "negativePrompt", "" }, // 同上
    { "croperX", "194" },
    { "croperY", "418" },
    { "croperHeight", "512" },
    { "croperWidth", "512" },
    { "useCroper", "false" },
    { "sdMaskBlur", "5" },
    { "sdStrength", "0.75" },
    { "sdSteps", "50" },
    { "sdGuidanceScale", "7.5" },
    { "sdSampler", "uni_pc" },
    { "sdSeed", "-1" },
    { "sdMatchHistograms", "false" },
    { "sdScale", "1" },
    { "cv2Radius", "5" },
    { "cv2Flag", "INPAINT_NS" },
    { "paintByExampleSteps", "50" },
    { "paintByExampleGuidanceScale", "7.5" },
    { "paintByExampleSeed", "-1" },
    { "paintByExampleMaskBlur", "5" },
    { "paintByExampleMatchHistograms", "false" },
    { "p2pSteps", "50" },
    { "p2pImageGuidanceScale", "1.5" },
    { "p2pGuidanceScale", "7.5" },
    { "controlnet_conditioning_scale", "0.4" },
    { "controlnet_method", "control_v11p_sd15_canny" }
};
                var multipartContent = new MultipartFormDataContent();



                multipartContent.Add(new ByteArrayContent(a), "image", "image.jpg");


                multipartContent.Add(new ByteArrayContent(b), "mask", "mask.jpg");



                // 添加固定的参数到multipartContent
                foreach (var kvp in fixedParams)
                {
                    multipartContent.Add(new StringContent(kvp.Value), kvp.Key);
                }

                var client = _clientFactory.CreateClient();
                var response = await client.PostAsync(Url, multipartContent);

                if (!response.IsSuccessStatusCode)
                {
                    _loggerHelper.Warn(log);
                    return default;
                }

                var result = await response.Content.ReadAsStreamAsync();

                return result;
            }
            catch (Exception ex)
            {
                _loggerHelper.Info("PostAsync" + DateTime.Now + "返回请求 Exception");
                _loggerHelper.Error($"post request exception  日志信息为{log}", ex);
                return default;
                throw;
            }
        }

        /// <summary>
        /// Post Request DataCenter
        /// </summary>
        /// <param name="Url">Url</param>
        /// <param name="Content">Content</param>
        /// <returns></returns>
        public async Task<T> PostDataCenterAsync<T>(string Url, HttpContent Content)
        {
            var log = "";
            try
            {
                //序列化成json
                //Content= JsonConvert.SerializeObject(Content);
                //log+=$"Url为{Url}，内容为{Content}"+Environment.NewLine;
                //创建请求的客户端
                _loggerHelper.Info($"PostDataCenterAsync{DateTime.Now}发送请求 Url:{Url} ,参数：{JsonConvert.SerializeObject(Content)}");

                var client = _clientFactory.CreateClient();
                client.Timeout = TimeSpan.FromMinutes(10);
                //创建请求类型
                client.DefaultRequestHeaders.Add("Appid", "generation");
                var response = await client.PostAsync(Url, Content);
                _loggerHelper.Info("PostDataCenterAsync" + DateTime.Now + "返回请求");
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                var result = await response.Content.ReadAsStringAsync();
                if (string.IsNullOrWhiteSpace(result))
                {
                    log += $"请求结果为空";
                    _loggerHelper.Warn(log);
                    return default;
                }
                log += $"请求结果为:{result}" + Environment.NewLine;
                try
                {
                    var data = JsonConvert.DeserializeObject<T>(result);
                    log += $"序列化成功";
                    _loggerHelper.Info(log);
                    return data;
                }
                catch
                {
                    _loggerHelper.Info("PostDataCenterAsync" + DateTime.Now + "返回请求 catch");
                    //不返回错误信息直接向外抛错误，外部捕获
                    throw;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.Info("PostDataCenterAsync" + DateTime.Now + "返回请求 Exception");
                _loggerHelper.Error($"post request exception,日志信息为{log},错误信息为{ex.Message}，运维测试URL:{Url}，Body:{JsonConvert.SerializeObject(Content)},Header:{Content.Headers}", ex);
                return default;
                throw;
            }
        }

        /// <summary>
        /// Get Request
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Url"></param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string Url)
        {
            var log = "";
            try
            {
                log += $"Url为{Url}" + Environment.NewLine;
                //创建请求的客户端
                var client = _clientFactory.CreateClient();
                //创建请求类型
                var response = await client.GetAsync(Url);
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                var result = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrWhiteSpace(result))
                {
                    log += $"请求结果为空{response.Content.ReadAsStringAsync().Result}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                log += $"请求结果为:{response.Content.ReadAsStringAsync().Result}" + Environment.NewLine;
                try
                {
                    var data = JsonConvert.DeserializeObject<T>(result);
                    log += $"序列化成功";
                    _loggerHelper.Info(log);
                    return data;
                }
                catch
                {
                    //不返回错误信息直接向外抛错误，外部捕获
                    throw;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.Error($"post request exception,日志信息为{log},错误信息为{ex.Message}", ex);
                return default;
                throw;
            }
        }

        /// <summary>
        /// Get Request DataCenter File
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public async Task<Stream> GetDataCenterFileAsync(string Url)
        {
            string log = "";
            try
            {
                log += $"Url为{Url}{Environment.NewLine}";

                // 创建 HttpClientHandler 以忽略 SSL 证书错误
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }
                };

                // 使用 HttpClientHandler 创建 HttpClient
                var client = new HttpClient(handler);

                // 创建请求类型
                var response = await client.GetAsync(Url);
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }

                var result = await response.Content.ReadAsStreamAsync();

                return result;
            }
            catch (Exception ex)
            {
                _loggerHelper.Error($"post request exception,日志信息为{log},错误信息为{ex.Message}", ex);
                return default;
                // throw 是多余的，因为捕获了异常并返回。
            }
        }

        /// <summary>
        /// Get Request DataCenter
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Url"></param>
        /// <returns></returns>
        public async Task<T> GetDataCenterAsync<T>(string Url)
        {
            var log = "";
            try
            {
                log += $"Url为{Url}" + Environment.NewLine;
                //创建请求的客户端
                var client = _clientFactory.CreateClient();
                //创建请求类型
                client.DefaultRequestHeaders.Add("Appid", "generation");
                var response = await client.GetAsync(Url);
                if (!response.IsSuccessStatusCode)
                {
                    log += $"请求失败{JsonConvert.SerializeObject(response)}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                var result = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrWhiteSpace(result))
                {
                    log += $"请求结果为空{response.Content.ReadAsStringAsync().Result}";
                    _loggerHelper.Warn(log);
                    return default;
                }
                log += $"请求结果为:{response.Content.ReadAsStringAsync().Result}" + Environment.NewLine;
                try
                {
                    var data = JsonConvert.DeserializeObject<T>(result);
                    log += $"序列化成功";
                    _loggerHelper.Info(log);
                    return data;
                }
                catch
                {
                    //不返回错误信息直接向外抛错误，外部捕获
                    throw;
                }
            }
            catch (Exception ex)
            {
                _loggerHelper.Error($"post request exception,日志信息为{log},错误信息为{ex.Message}", ex);
                return default;
                throw;
            }
        }
    }
}